<template>
	<om-addpage :scrollTop="scrollTop" style="padding-top: 35px;" :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit">
		<om-autoform ref="autoform" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
	</om-addpage>
</template>

<script>
	import {
		errorModal,
		ignoreHtml,
		getUrl,
		confirmModal,
		ptFloat,
		minusF
	} from '@/static/js/common.js';
	import {
		changeConfigAttr,
		buildFormData,
		formValidation,
		tranferToEditors,
		changeEditor,
		setSubmitSubValue,
		configSelectData,
		hasValue,
		hasEditor,
		formShowLoading,
		getFormFields,
		formModelLoad,
		getWorkCacheKey
	} from '@/static/js/formUtil.js';
	import urlUtil from '@/static/js/urlUtil.js';
	import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';
	export default {
		provide() {
			return {
				formPage: this
			};
		},
		data() {
			return buildFormData({
				scrollTop: 0,
				instId: "",
				editId: '',
				subDay: "",
				month: "",
				yearFlag: false,
				instCache:'obj-month-tmonthlyPlan-inst-cache'
			})
		},
		computed: {
			...mapState(useLoginUserStore, ['userName', 'userId'])
		},
		methods: {
			verifyMonth(item) {
				let _that = this
				_that.month = item.referNum
				_that.om.request(
					"tmonthlyPlan/verifyMonth", {
						year: Number(_that.$refs.autoform.formdata.year),
						monthCode: item.code,
						instId: _that.$refs.autoform.formdata.instId,
						editId: _that.editId ? _that.editId : ''
					},
					"post"
				).then(res => {
					if (res.succeed && res.value) {
						errorModal(_that, "提示信息", ignoreHtml(res.value), () => {
							_that.$refs.autoform.clear('title_basic', "monthCode")
						})
					} else {
						// _that.onSelectMonth(item)
					}
				})
			},
			formSubmit() {
				let _that = this
				_that.formdata.yearFlag = _that.yearFlag
				_that.$refs.autoform.formdata.yearFlag = _that.yearFlag
				_that.om.formSave("/tmonthlyPlan/addTmonthlyPlan", _that.formdata, _that)
			},
			verifyWorkStr() {
				let _that = this
				if (!_that.$refs.autoform.formdata.monthCode) {
					_that.om.toast("请先选择月份", 3000)
					return false
				} else {
					return true
				}
			},
			verifyIndex() {
				let _that = this
				if (!_that.$refs.autoform.formdata.monthCode) {
					_that.om.toast("请先选择月份", 3000)
					return false
				} else {
					return true
				}
			},
			getWorkParam() {
				let _that = this
				return {
					dataList: JSON.stringify(_that.subEditorObj['title_index'].workList),
					subDay: _that.subDay,
					month: _that.month,
					busCode:_that.busCode,
					userId: _that.$refs.autoform.formdata.userId,
				}
			},
			getWorkParam1() {
				let _that = this
				return {
					userId: _that.userId,
					instId: _that.$refs.autoform.formdata.instId,

				}
			},
			verifyChart() {
				let _that = this
				if (!_that.$refs.autoform.formdata.instId || !_that.$refs.autoform.formdata.year) {
					_that.om.toast("请先选择部门名称" + "和计划年度", 3000)
					return false
				} else {
					return true
				}
			},
			onSelectMonth(item) {
				let _that = this
				_that.verifyMonth(item)
				_that.om.request(
					"tmonthlyPlan/getIndexList", {
						instId: _that.$refs.autoform.formdata.instId,
						year: _that.$refs.autoform.formdata.year,
						monthCode: item.code
					}
				).then(res => {
					_that.$refs.autoform.clear("title_mission", "mission")
					_that.$refs.autoform.clear("title_target", "target")
					if (res.value.target) {
						_that.$refs.autoform.formdata.target = res.value.target || ''
						_that.$refs.autoform.formdata.mission = res.value.mission || ''
					}
					let objFormCode = JSON.parse(uni.getStorageSync('objFormCode'))
					if (res.value.indexList) {
						if (Object.prototype.toString.call(res.value.indexList) === '[object Array]') {
							for (let index in res.value.indexList) {
								res.value.indexList[index].orderNum = objFormCode.DICT_CODE_R + (Number(index) + 1) || ''
								if (!res.value.indexList[index].deleteInMonthProj) {
									_that.$set(res.value.indexList[index], "showDel", false)
								}else{
									_that.$set(res.value.indexList[index], "showDel", true)
								}
							}
							_that.yearFlag = true
							uni.setStorageSync('objIndexList', "indexList")
							_that.$set(_that.subEditorObj["title_index"], "workList", res.value.indexList)
						} else {
							_that.yearFlag = false
							uni.setStorageSync('objIndexList', "")
							_that.$set(_that.subEditorObj["title_index"], "workList", [])
						}
					}
					if (res.value.workList) {
						if (Object.prototype.toString.call(res.value.workList) === '[object Array]') {
							for (let n in res.value.workList) {
								res.value.workList[n].orderNum = objFormCode.DICT_CODE_Y + (Number(n) + 1 || '')
							}
							_that.$set(_that.subEditorObj["title_work"], "workList", res.value.workList)
						} else {
							_that.$set(_that.subEditorObj["title_work"], "workList", [])
						}
					}
				})
			},
			clearInstId(){
				let _that = this
				_that.$refs.autoform.clear("title_basic", "year")
				_that.$refs.autoform.clear("title_basic", "monthCode")
				_that.$refs.autoform.clearGroup("title_index")
				_that.$refs.autoform.clearGroup("title_work")
			},
			onSelectInst(item) {
				let _that = this
				_that.$refs.autoform.formdata.instId = item.id
				_that.$refs.autoform.formdata.instName = item.text
				
				_that.om.request(
					"orgInstPosUserOfficial/getPrimaryData", {
						instId: item.id,
					}
				).then(res => {
					if (res.succeed) {
						_that.$refs.autoform.formdata.userId = res.value.userId
						_that.$refs.autoform.formdata.userPosName = res.value.userPosName
						_that.$refs.autoform.formdata.posId = res.value.posId						
					}
				})
				

				let date = new Date()
				let yearList = [{
					name: Number(date.getFullYear()),
					value: Number(date.getFullYear())
				}, {
					name: Number(date.getFullYear()) + 1,
					value: Number(date.getFullYear()) + 1
				}]
				_that.$refs.autoform.changeEditor("title_basic", "year", "data", configSelectData(yearList, "value", "name"))
				_that.$refs.autoform.initSelectIndex("title_basic", "year")
			},
			getMonthDataList(item) {
				let _that = this
				_that.om.request(
					"dictZero/getRecentMonth", {
						year: item.value
					}
				).then(res => {
					_that.$refs.autoform.changeEditor("title_basic", "monthCode", "data", configSelectData(res, "code", "dicname"))
					_that.$refs.autoform.initSelectIndex("title_basic", "monthCode")
					if (!_that.edit) {
						_that.getDataList()
					}
				})
			},
			getYearDataList(item){
				let _that = this
				_that.om.request(
					"dictZero/getListByCode",
					{
						code:'35803'
					}
				).then(res=>{
					_that.$refs.autoform.changeEditor("title_basic","monthCode","data",configSelectData(res,"code","dicname"))
					_that.$refs.autoform.initSelectIndex("title_basic","monthCode")
					if(!_that.edit){
						_that.getDataList()
					}
				})
			},
			onSelectYear(item){
				let _that = this
				let date = new Date()
				let nowYear = Number(date.getFullYear());
				if(item.value != nowYear){
					uni.showModal({
						title: '选择的' + nowYear + '年不是当前年，是否继续选择？',
						showCancel: true,
						success(res){
							if(res.confirm){
								_that.getYearDataList(item)
							}else{
								_that.$refs.autoform.clear("title_basic", "year")
								_that.$refs.autoform.clear("title_basic", "monthCode")
							}
						}
					})
				}else{
					_that.getYearDataList(item)
				}
			},
			getPosList() {
				let _that = this
				_that.om.request(
					"tmonthlyPlan/getInstList"
				).then(res => {
					_that.$refs.autoform.changeEditor("title_basic", "instId", "data", configSelectData(res, "id", "text"))
					_that.$refs.autoform.initSelectIndex("title_basic", "instId")
				})
			},
			getDataList() {
				let _that = this
				_that.om.request(
					"tmonthlyPlan/findAllIndexEchart", {
						posId: _that.$refs.autoform.formdata.posId,
						year: _that.$refs.autoform.formdata.year
					},
					"post"
				).then(res => {
					let arr = []
					for (let index in res.value) {
						let obj = {
							categories: [],
							series: [],
							title: "",
							type: 'line'
						}
						obj.categories = res.value[index].xAxis.data
						obj.series = res.value[index].series
						obj.title = res.value[index].title
						obj.name = res.value[index].yAxis.name
						obj.listTitle = ["折线图", "柱状图"]
						obj.listValue = ["line", "column"]
						arr.push(obj)
					}
					if(_that.subEditorObj["title_chart"]){
						_that.subEditorObj["title_chart"].workList = arr
					}
				})
			},
			initLoad(options) {
				let _that = this
				uni.setStorageSync('objIndexList', "")
				let ajaxArr = [
					urlUtil.zposUrl(options.code),
					urlUtil.dataDictInitValueUrl("DD021014001"),
					{
						url:"commonForm/getInitParamMap",
						param:{
							formCode:options.code
						},
					}
				]
				let fileId = options.fileId
				if (fileId) {
					ajaxArr.push({
						url: "tmonthlyPlan/getInfo",
						param: {
							id: fileId
						},
						method: "post"
					})
					_that.editId = fileId
				}
				formModelLoad(ajaxArr, function(res, mainData) {
					uni.setStorageSync('objFormCode', JSON.stringify(res[2].value))
					changeEditor("topinfo","zposId","data",configSelectData(res[0],"id","posname"),mainData)
					_that.subDay = res[1].value
					// changeEditor("topinfo", "zuserId", {
					// 	defaultValue: _that.userId,
					// 	defaultName: _that.userName
					// }, null, mainData)
					if (_that.subConfigData["title_index"]) {
						let att = {
							getWorkParam: "getWorkParam1",
							showDel:true
						}
						let configData = _that.subConfigData["title_index"]
						if (hasEditor("title_index", "indexId", configData)) {
							_that.$set(att, "titleTemplate", "<%=indexName || ''%>")
						}
						changeEditor("title_index", "indexStr", att, mainData)
					}
					if (_that.subConfigData["title_work"]) {
						let att1 = {
							getWorkParam: "getWorkParam",
						}
						let configData = _that.subConfigData["title_work"]
						if (hasEditor("title_work", "workName", configData)) {
							_that.$set(att1, "titleTemplate", "<%=workName || ''%>")
						}
						changeEditor("title_work", "workStr", att1, mainData)
					}
					changeEditor("title_basic", "instId",{
						link:'../../public/search/search',
						"linkParam":{
							other:JSON.stringify({}),
							url:'tmonthlyPlan/getInstList',
							namefield:'text',
							initload:true,
							cachename:_that.instCache
						}
					},null,mainData)
					if (fileId) {
						let fieldArr = getFormFields(mainData)
						fieldArr.push("id", "posId")
						for (let index in res[3].value.tmonthlyPlan) {
							if (fieldArr.includes(index)) {
								_that.$refs.autoform.$set(_that.$refs.autoform.formdata, index, res[3].value.tmonthlyPlan[index])
								_that.$set(_that.formdata, index, res[3].value.tmonthlyPlan[index])
							}
						}
						_that.$refs.autoform.formdata.target = res[3].value.target
						let dataList = _that._.cloneDeep(res[3].value.workList)
						_that.subEditorObj["title_work"].workList = dataList
						_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "workStr", JSON.stringify(dataList))
						_that.$set(_that.formdata, "workStr", JSON.stringify(dataList))
						let indexList = _that._.cloneDeep(res[3].value.indexList)
						for (let item of indexList) {
							if (!item.deleteInMonthProj) {
								_that.$set(item, "showDel",false)
							}else{
								_that.$set(item, "showDel",true)
							}
						}
						_that.subEditorObj["title_index"].workList = indexList
						_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "indexStr", JSON.stringify(indexList))
						changeEditor("topinfo","zposId","type","labelbox",mainData)
						
						if(res[3].value.tmonthlyPlan.yearFlag){
							_that.yearFlag = true
							uni.setStorageSync('objIndexList', "indexList")
						}else{
							_that.yearFlag = false
							uni.setStorageSync('objIndexList', "")
						}
						
						_that.$nextTick(function() {
							_that.$refs.autoform.initSelectIndex("topinfo","zposId")
							_that.getPosList()
							_that.getDataList()
							// _that.onSelectInst({
							// 	instId: _that.$refs.autoform.formdata.instId,
							// 	userPosName: _that.$refs.autoform.formdata.userPosName
							// })
							_that.onSelectInst({
								id: _that.$refs.autoform.formdata.instId,
								text: _that.$refs.autoform.formdata.instName
							})
							_that.getYearDataList({value:_that.$refs.autoform.formdata.year})
							_that.getMonthDataList({
								value: _that.$refs.autoform.formdata.year
							})
							let month = _that.$refs.autoform.formdata.monthName.substring(0, _that.$refs.autoform.formdata.monthName.length -
								1)
							_that.month = month
							
						})
					}
				}, options)
			}
		},
		onLoad(options) {
			let _that = this
			_that.initLoad(options)
		},
		onPageScroll(e) {
			if (e.scrollTop > 200) {
				this.scrollTop = e.scrollTop
			} else {
				this.scrollTop = 0
			}
		},
		onUnload() {
			//#ifdef APP-PLUS
			let _that = this;
			if (_that.$refs.autoform) {
				for (var fieldId in _that.subEditorObj) {
					uni.removeStorage({
						key: getWorkCacheKey(fieldId)
					});
				}
			}
			//#endif
		},
		onShow() {
			let _that = this
			for (let fieldId in _that.subEditorObj) {
				let editor = _that.subEditorObj[fieldId]
				uni.getStorage({
					key: getWorkCacheKey(fieldId),
					success: function(res) {
						if (fieldId === "title_index") {
							for (let item of res.data) {
								if (item.logicRelationshipName) {
									if (item.targetValueCode) {
										item.targetValueName = item.logicRelationshipName + item.targetValueCode + item.indexUnitName
									}
									if (item.challengeTargetCode) {
										item.challengeTargetName = item.logicRelationshipName + item.challengeTargetCode + item.indexUnitName
									}
								} else if (item.prefix) {
									if (item.targetValueCode) {
										item.targetValueName = item.prefix + item.targetValueCode + item.suffix
									}
									if (item.challengeTargetCode) {
										item.challengeTargetName = item.prefix + item.challengeTargetCode + item.suffix
									}
								}
								if (!item.deleteInMonthProj) {
									_that.$set(item, "showDel", item.deleteInMonthProj)
								}
							}
						}
						editor.workList = res.data;
						uni.removeStorage({
							key: getWorkCacheKey(fieldId)
						});
					}
				});
				uni.getStorage({
					key:_that.instCache,
					success:(res)=>{
						if(res.data){
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.instId = d.id
							formdata.instName = d.text
							_that.onSelectInst({id:d.id,text:d.text})
						}
					}
				})
			}
		}
	}
</script>

<style></style>
